import sheetmanage from './sheetmanage'
import menuButton from './menuButton'
import Store from '../store'
import { modelHTML } from './constant'
import { selectionCopyShow } from './select'
import dataVerificationCtrl from './dataVerificationCtrl'
import formula from '../global/formula'
import editor from '../global/editor'
import { getSheet } from '../global/api'
import { replaceHtml } from '../utils/util'
import locale from '../locale/locale'
const _locale = locale()
const dvText = _locale.dataVerification
const locale_toolbar = _locale.toolbar
const locale_button = _locale.button

// Get the pixel value per millimeter
function dictInitial() {
  // 数据字典弹框
  $('#luckysheet-icon-dict').click(function() {
    if ($('#luckysheet-dict-dialog')) {
      $('#luckysheet-dict-dialog').remove()
    }
    let content = `<div class="box">
                    <div class="box-item" style="border-top:1px solid #E1E4E8;">
                      <div class="box-item-title">${dvText.cellRange}</div>
                      <div id="data-dict-range" class="range">
                        <input class="formulaInputFocus" spellcheck="false">
                        <i class="fa fa-table" aria-hidden="true" title="${dvText.selectCellRange}"></i>
                      </div>
                    </div>
                    <div class="box-item">
                      <div class="box-item-title">${dvText.placeholderType}</div>
                      <div class="show-box-item">
                        <select id="data-verification-dict-select" style="margin-bottom: 10px">
                          <option value="DICT">${dvText.dict}</option>
                          <option value="TREEDICT">${dvText.treeDict}</option>
                          <option value="NEQ">${dvText.neq}</option>
                          <option value="REGION">${dvText.region}</option>
                        </select>
                        <div class="range">
                          <input class="formulaInputFocus data-verification-value2" placeholder="${dvText.placeholder}" spellcheck="false">
                        </div>
                        <div class="multi">
                          <input type="checkbox" id="data-verification-dict" class="data-verification-multi">
                          <label for="data-verification-multi">${dvText.allowMultiSelect}</label>
                        </div>
                      </div>
                    </div>
                    <div class="box-item">
                      <div class="check">
                        <input type="checkbox" id="data-verification-prohibitInput">
                        <label for="data-verification-prohibitInput">${dvText.prohibitInput}</label>
                      </div>
                      <div class="check">
                        <input type="checkbox" id="data-verification-hint-show">
                        <label for="data-verification-hint-show">${dvText.hintShow}</label>
                      </div>
                      <div class="data-verification-hint-text" style="display: none">
                        <input type="text" placeholder="${dvText.placeholder5}">
                      </div>
                    </div>
                  </div>`
    $('body')
      .first()
      .append(
        replaceHtml(modelHTML, {
          id: 'luckysheet-dict-dialog',
          addclass: 'luckysheet-dialog',
          title: locale_toolbar.dictRender,
          content: content,
          botton:
            '<button id="luckysheet-dict-dialog-confirm" class="btn btn-primary">' +
            locale_button.confirm +
            '</button><button class="btn btn-default luckysheet-model-close-btn">' +
            locale_button.cancel +
            '</button>',
          style: 'z-index:100003',
        })
      )
    $('#luckysheet-modal-dialog-mask').show()
    let $t = $('#luckysheet-dict-dialog')
        .find('.luckysheet-modal-dialog-content')
        .css('min-width', 400)
        .end(),
      myh = $t.outerHeight(),
      myw = $t.outerWidth()
    let winw = $(window).width(),
      winh = $(window).height()
    let scrollLeft = $(document).scrollLeft(),
      scrollTop = $(document).scrollTop()
    $('#luckysheet-dict-dialog').css({
      left: (winw + scrollLeft - myw) / 2,
      top: (winh + scrollTop - myh) / 3,
    })
    menuButton.dataAllocation()
  })
  // 数据字典弹框确认
  $(document)
    .off('click.dvDictConfirm')
    .on('click.dvDictConfirm', '#luckysheet-dict-dialog-confirm', function(e) {
      let rangeTxt = $('#luckysheet-dict-dialog #data-dict-range input')
        .val()
        .trim()
      let range = menuButton.getRangeByTxt(rangeTxt)

      if (range.length == 0) {
        tooltip.info(
          '<i class="fa fa-exclamation-triangle"></i>',
          dvText.selectCellRange2
        )
        return
      }
      let str = range[range.length - 1].row[0],
        edr = range[range.length - 1].row[1],
        stc = range[range.length - 1].column[0],
        edc = range[range.length - 1].column[1]
      let d = editor.deepCopyFlowData(Store.flowdata)

      if (str < 0) {
        str = 0
      }

      if (edr > d.length - 1) {
        edr = d.length - 1
      }

      if (stc < 0) {
        stc = 0
      }

      if (edc > d[0].length - 1) {
        edc = d[0].length - 1
      }

      let type2 = null,
       type3 = null,
        value1 = '',
        value2 = ''

      type2 = $('#luckysheet-dict-dialog #data-dict-dict').is(':checked')
      type3 = $('#data-verification-custom-select').val()
      value1 = $('#data-verification-dict-select').val()
      value2 = value2 = $('#luckysheet-dict-dialog  .data-verification-value2')
        .val()
        .trim()

      let prohibitInput = $(
        '#luckysheet-dict-dialog #data-verification-prohibitInput'
      ).is(':checked')
      let hintShow = $(
        '#luckysheet-dict-dialog #data-verification-hint-show'
      ).is(':checked')
      let hintText = ''

      if (hintShow) {
        hintText = $(
          '#luckysheet-dict-dialog .data-verification-hint-text input'
        )
          .val()
          .trim()
      }

      let item = {
        type2: type2,
        type3: type3,
        value1: value1,
        value2: value2,
        checked: false,
        prohibitInput: prohibitInput,
        hintShow: hintShow,
        hintText: hintText,
      }
      let historyDataVerification = $.extend(
        true,
        {},
        menuButton.dataVerification
      )
      let currentDataVerification = $.extend(
        true,
        {},
        menuButton.dataVerification
      )

      for (let r = str; r <= edr; r++) {
        for (let c = stc; c <= edc; c++) {
          currentDataVerification[r + '_' + c] = item
        }
      }
      // 以下情况默认是整列配置
      if (d.length - edr < 5 && stc == edc) {
        // 数据字典
        let current = getSheet(Store.currentSheetIndex)
        if (current.dataVerification) {
          current.dataVerification[stc] = item
        } else {
          let dataVerification = {}
          dataVerification[stc] = item
          current.dataVerification = dataVerification
        }
      }
      dataVerificationCtrl.ref(
        historyDataVerification,
        currentDataVerification,
        Store.currentSheetIndex
      )
      $('#luckysheet-modal-dialog-mask').hide()
      $('#luckysheet-dict-dialog').hide()
    })

  // 数据字典选取确认框
  $(document)
    .off('click.dvdictRConfirm')
    .on(
      'click.dvdictRConfirm',
      '#luckysheet-dictrange-dialog-confirm',
      function(e) {
        let dataSource = $(this).attr('data-source')
        let txt = $(this)
          .parents('#luckysheet-dict-dialog')
          .find('input')
          .val()
        if (menuButton.getRangeByTxt(txt).length > 1) {
          tooltip.info(
            '<i class="fa fa-exclamation-triangle"></i>',
            '不能对多重选择区域执行此操作，请选择单个区域，然后再试'
          )
          return
        }

        if (dataSource == '0') {
          $('#luckysheet-dict-dialog #data-dict-range input').val(txt)
        } else if (dataSource == '1') {
          $('#luckysheet-dict-dialog .show-box-item-dropdown .range input').val(
            txt
          )
        }

        $('#luckysheet-dict-dialog').hide()
        $('#luckysheet-modal-dialog-mask').show()
        $('#luckysheet-dict-dialog').show()

        if (
          formula.rangetosheet != null &&
          formula.rangetosheet != Store.currentSheetIndex
        ) {
          sheetmanage.changeSheetExec(formula.rangetosheet)
          formula.rangetosheet = null
        }

        let range = []
        selectionCopyShow(range)
      }
    )

  //单元格范围
  $(document)
    .off('click.dvRangeDict')
    .on('click.dvRangeDict', '#data-dict-range .fa-table', function(e) {
      $('#luckysheet-dict-dialog').hide()
      let dataSource = '0'
      let txt = $(this)
        .siblings('input')
        .val()
        .trim()
      console.log('text', txt)
      menuButton.dictRangeDialog(dataSource, txt)

      menuButton.selectRange = []

      let range = menuButton.getRangeByTxt(txt)

      formula.rangetosheet = Store.currentSheetIndex

      if (!range || range[0]?.sheetIndex != Store.currentSheetIndex) {
        sheetmanage.changeSheetExec(range[0].sheetIndex)
      }
      if (range.length > 0) {
        for (let s = 0; s < range.length; s++) {
          let r1 = range[s].row[0],
            r2 = range[s].row[1]
          let c1 = range[s].column[0],
            c2 = range[s].column[1]

          let row = Store.visibledatarow[r2],
            row_pre = r1 - 1 == -1 ? 0 : Store.visibledatarow[r1 - 1]
          let col = Store.visibledatacolumn[c2],
            col_pre = c1 - 1 == -1 ? 0 : Store.visibledatacolumn[c1 - 1]

          menuButton.selectRange.push({
            left: col_pre,
            width: col - col_pre - 1,
            top: row_pre,
            height: row - row_pre - 1,
            left_move: col_pre,
            width_move: col - col_pre - 1,
            top_move: row_pre,
            height_move: row - row_pre - 1,
            row: [r1, r2],
            column: [c1, c2],
            row_focus: r1,
            column_focus: c1,
          })
        }
      }
      selectionCopyShow(menuButton.selectRange)
    })
  $(document)
    .off('click.dvDictFGClose')
    .on('click.dvDictFGClose', '#luckysheet-dictrange-dialog-close', function(
      e
    ) {
      $('#luckysheet-dataVerificationRange-dialog').hide()
      $('#luckysheet-modal-dialog-mask').show()
      $('#luckysheet-dict-dialog').show()

      if (
        formula.rangetosheet != null &&
        formula.rangetosheet != Store.currentSheetIndex
      ) {
        sheetmanage.changeSheetExec(formula.rangetosheet)
        formula.rangetosheet = null
      }

      let range = []
      selectionCopyShow(range)
    })
  //选中单元格时显示提示语
  $(document)
    .off('change.dicthintShow')
    .on('change.dicthintShow', '#data-verification-hint-show', function(e) {
      if (this.checked) {
        $('#luckysheet-dict-dialog .data-verification-hint-text').show()
      } else {
        $('#luckysheet-dict-dialog .data-verification-hint-text').hide()
      }
    })
}

export { dictInitial }
